{% extends "sysadmin/sys_org_info_base.html" %}
{% load i18n seahub_tags %}

{% block right_panel %}
<div class="tabnav">
    <ul class="tabnav-tabs">
        <li class="tabnav-tab tabnav-tab-cur"><a href="{% url 'sys_org_info_user' org.org_id %}">{% trans "Members" %}</a></li>
        <li class="tabnav-tab"><a href="{% url 'sys_org_info_group' org.org_id %}">{% trans "Groups" %}</a></li>
        <li class="tabnav-tab"><a href="{% url 'sys_org_info_library' org.org_id %}">{% trans "Libraries" %}</a></li>
        <li class="tabnav-tab"><a href="{% url 'sys_org_info_setting' org.org_id %}">{% trans "Settings" %}</a></li>
    </ul>
    <div class="fright">
        <button id="add-user-btn">{% trans "Add user" %}</button>
    </div>
</div>

<table>
    <tr>
        <th width="25%">{% trans "Email" %}</th>
        <th width="10%">{% trans "Status" %}</th>
        <th width="20%">{% trans "Space Used" %}</th>
        <th width="25%">{% trans "Create At / Last Login" %}</th>
        <th width="20%">{% trans "Operations" %}</th>
    </tr>

    {% for user in users %}
    <tr data-userid="{{user.email}}" data-url="{% url 'api-v2.1-admin-org-user' org.org_id user.email %}">
        <td><a href="{% url 'user_info' user.email %}">{{ user.email }}</a></td>
        <td>
            <div class="user-status">
              {% if user.is_active %}
                <span class="user-status-cur-value">{% trans "Active" %}</span>
              {% else %}
                <span class="user-status-cur-value">{% trans "Inactive" %}</span>
              {% endif %}
                <span title="{% trans "Edit" %}" class="user-status-edit-icon op-icon sf2-icon-edit vh"></span>
            </div>
            <select name="permission" class="user-status-select hide">
                <option value="true" {% if user.is_active %}selected="selected"{% endif %}>{% trans "Active" %}</option>
                <option value="false" {% if not user.is_active %}selected="selected"{% endif %}>{% trans "Inactive" %}</option>
            </select>
        </td>
        <td>
            {{ user.self_usage|seahub_filesizeformat }} {% if user.quota > 0 %} / {{ user.quota|seahub_filesizeformat }} {% endif %}
        </td>
        <td style="font-size:11px;">
        {{ user.ctime|tsstr_sec }} / {% if user.last_login %}{{user.last_login|translate_seahub_time}} {% else %} -- {% endif %}
        </td>
        <td>
          {% if not user.is_self %}
          <a href="#" class="remove-user-btn op vh">{% trans "Delete" %}</a>
          <a href="#" class="reset-user-btn op vh" data-url="{% url 'user_reset' user.email %}" data-target="{{ user.email }}">{% trans "ResetPwd" %}</a>
          {% endif %}
        </td>
    </tr>
    {% endfor %}
</table>

<div id="activate-msg" class="hide">
    <p>{% trans "Activating..., please wait" %}</p>
</div>

<form id="add-user-form" action="" method="post" class="hide">{% csrf_token %}
    <h3>{% trans "Add user" %}</h3>
    <label for="id_email">{% trans "Email" %}</label><br />
    <input type="text" name="email" id="id_email" class="input" /><br />

    <label for="id_name">{% trans "Name(optional)" %}</label><br />
    <input type="text" name="name" id="id_name" class="input" /><br />

    <label for="id_password1">{% trans "Password" %}</label>
    <div class="passwd-wrapper">
        <input type="password" name="password1" id="id_password1" class="passwd input" />
        <span title="{% trans "Show" %}" class="icon-eye show-or-hide-password cspt"></span>
        <span title="{% trans "Generate a random password" %}" class="icon-magic generate-random-password cspt"></span>
    </div>
    <label for="id_password2">{% trans "Confirm Password" %}</label><br />
    <input type="password" name="password2" id="id_password2" class="input" /><br />
    <p class="error hide"></p>
    <button type="submit" class="submit">{% trans "Submit" %}</button>
</form>
{% endblock %}

{% block extra_script %}
<script type="text/javascript">
{% include 'sysadmin/sys_org_set_quota_js.html' %}

$('#add-user-btn').on('click', function() {
    $('#add-user-form').modal();
    $('#simplemodal-container').css({'width':'auto', 'height':'auto'});
});

$('#add-user-form .show-or-hide-password').on('click', function() {
    var icon = $(this),
        passwd_input = $('input[name=password1], input[name=password2]', $('#add-user-form'));
    icon.toggleClass('icon-eye icon-eye-slash');
    if (icon.hasClass('icon-eye')) {
        icon.attr('title', "{% trans "Show" %}");
        passwd_input.prop('type', 'password');
    } else {
        icon.attr('title', "{% trans "Hide" %}");
        passwd_input.prop('type', 'text');
    }
});

$('#add-user-form .generate-random-password').on('click', function() {
    var form = $('#add-user-form');
    var random_password = '';
    var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz0123456789';
    for (var i = 0; i < 8; i++) {
        random_password += possible.charAt(Math.floor(Math.random() * possible.length));
    }
    $('input[name=password1], input[name=password2]', form).prop('type', 'text').val(random_password);
    $('.show-or-hide-password', form)
    .attr('title', "{% trans "Hide" %}")
    .removeClass('icon-eye').addClass('icon-eye-slash');
});

$('#add-user-form').on('submit', function() {
    var form = $(this),
        form_id = $(this).attr('id'),
        org_id = {{ org.org_id }},
        email = $.trim(form.children('[name="email"]').val()),
        name = $.trim($('[name="name"]', form).val()),
        pwd1 = $.trim(form.find('[name="password1"]').val()),
        pwd2 = $.trim(form.children('[name="password2"]').val());

    if (!email) {
        apply_form_error(form_id, "{% trans "Email cannot be blank" %}");
        return false;
    }
    if (!pwd1) {
        apply_form_error(form_id, "{% trans "Password cannot be blank" %}");
        return false;
    }
    if (!pwd2) {
        apply_form_error(form_id, "{% trans "Please enter the password again" %}");
        return false;
    }
    if (pwd1 != pwd2) {
        apply_form_error(form_id, "{% trans "Passwords do not match" %}");
        return false;
    }

    var submit_btn = $(this).find('[type="submit"]');
    var url = "{% url 'api-v2.1-admin-org-users' org.org_id %}";
    disable(submit_btn);
    $.ajax({
        url: url,
        type: 'POST',
        datatype: 'json',
        cache: false,
        beforeSend: prepareCSRFToken,
        data: {
            'email': email,
            'name': name,
            'password': pwd1
        },
        success: function(data) {
            location.reload(true);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            if (jqXHR.responseText) {
                apply_form_error(form_id, JSON.parse(jqXHR.responseText).error_msg);
            } else {
                apply_form_error(form_id, "{% trans "Failed. Please check the network." %}");
            }
            enable(submit_btn);
        }
    });
    return false;
});

$('.remove-user-btn').on('click', function() {
    var _this = $(this),
        uid = _this.parents('tr').attr('data-userid'),
        url = _this.parents('tr').attr('data-url'),
        popupTitle = "{% trans "Delete User" %}",
        popupContent = "{% trans "Are you sure you want to delete %s ?" %}".replace('%s', '<span class="op-target ellipsis ellipsis-op-target" title="' + HTMLescape(uid) + '">' + HTMLescape(uid) + '</span>');

    var yesCallback = function() {
        $.ajax({
            url: url,
            type: 'DELETE',
            dataType: 'json',
            cache: false,
            beforeSend: prepareCSRFToken,
            success: function() {
                _this.closest('tr').remove();
                feedback("{% trans "Successfully deleted 1 item." %}", 'success');
            },
            error: function(xhr, textStatus, errorThrown) {
                ajaxErrorHandler(xhr, textStatus, errorThrown);
            },
            complete: function() {
                $.modal.close();
            }
        });
    };
    showConfirm(popupTitle, popupContent, yesCallback);
    return false;
});

addConfirmTo($('.reset-user-btn'), {
    'title':"{% trans "Password Reset" %}",
    'con':"{% trans "Are you sure you want to reset the password of %s ?" %}",
    'post': true // post request
});

$('.user-status-edit-icon').on('click', function() {
    $(this).parent().addClass('hide');
    $(this).parent().next().removeClass('hide'); // show 'select'
});

$('.user-status-select').on('change', function() {
    var select = $(this),
        select_val = select.val(),
        uid = select.parents('tr').attr('data-userid'),
        url = select.parents('tr').attr('data-url'),
        $select_prev = $(this).prev('.user-status'); // .user-status, .user-role

    if (select_val == 'true') {
        // show activating popup
        $('#activate-msg').modal();
        $('#simplemodal-container').css({'height':'auto'});
    }

    $.ajax({
        url: url,
        type: 'PUT',
        data: {'active': select_val},
        dataType: 'json',
        cache: false,
        beforeSend: prepareCSRFToken,
        success: function(data) {
            feedback("{% trans "Edit succeeded" %}", 'success');
            $('.user-status-cur-value', $select_prev).html(select.children('option[value="' +select.val() + '"]').text());
            select.addClass('hide');
            $select_prev.removeClass('hide');
            $.modal.close();
        },
        error: function() {
            feedback("{% trans 'Edit failed.' %}", 'error');
            select.addClass('hide');
            select.prev().removeClass('hide');
            $.modal.close();
        }
    });
});

$(document).on('click', function(e) {
    var target = e.target || event.srcElement;
    // target can't be edit-icon
    if (!$('.user-status-edit-icon, .user-status-select').is(target)) {
        $('.user-status').removeClass('hide');
        $('.user-status-select').addClass('hide');
    }
});

</script>
{% endblock %}
